package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.app.util.UserContext;
import cn.wolfcode.trip.base.domain.Strategy;
import cn.wolfcode.trip.base.domain.StrategyLike;
import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.service.IStrategyLikeService;
import cn.wolfcode.trip.base.service.IStrategyService;
import cn.wolfcode.trip.base.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
@RequestMapping("/strategyLikes")
public class StrategyLikeController {

    @Autowired
    private IStrategyLikeService strategyLikeService;

    @Autowired
    private IStrategyService strategyService;

    /**
     * 攻略点赞
     * @param strategyId
     * @param userId
     * @return
     */
    @PostMapping
    public JsonResult StrategyLike(Long strategyId, Long userId){
        JsonResult jsonResult = new JsonResult();
        User currentUser = UserContext.getCurrentUser();
        Integer likeCount = strategyService.queryLikeCount(strategyId);
        if (likeCount == null){
            likeCount = 0 ;
        }
        StrategyLike strategyLike = strategyLikeService.queryLike(strategyId,userId);
        if (strategyLike == null){
            //如果没有该点赞信息就保存该点赞信息
            StrategyLike strategyLike1 = new StrategyLike();
            Strategy strategy = strategyService.getById(strategyId);
            strategyLike1.setCreateTime(new Date());
            strategyLike1.setStrategy(strategy);
            strategyLike1.setUser(currentUser);
            strategyLikeService.insert(strategyLike1);
            //攻略点赞数加一
            strategyService.updateLike(likeCount+1,strategyId);
            return jsonResult;
        }else {
            //有就删除该点赞信息
            strategyLikeService.deleteLike(strategyId,userId);
            //攻略点赞数减一
            strategyService.updateLike(likeCount-1,strategyId);
            return jsonResult.mark(new String(""));
        }
    }

    @GetMapping
    public JsonResult queryLike(Long strategyId,Long userId){
        JsonResult jsonResult = new JsonResult();
        StrategyLike strategyLike = strategyLikeService.queryLike(strategyId, userId);
        if (strategyLike!=null){
            return jsonResult;
        } else {
            return jsonResult.mark(new String(""));
        }
    }

}
